// Package user 存放用户 Model 相关逻辑
package models

import (
	"books/pkg/database"
)

// Book 用户模型
type Book struct {
	BaseModel

	Name            string    `json:"name"`
	Author          string    `json:"author"`
	CategoryID      uint64    `json:"category_id"`
	PublicationYear int       `json:"publication_year"`
	Available       int       `json:"available"`
	Category        *Category `json:"category" gorm:"foreignKey:CategoryID"`
	CommonTimestampsField
}

func GetBooks(name string, author string, category_id uint64, available bool) ([]Book, error) {
	var books []Book

	db := database.DB.Model(Book{}).Preload("Category")

	if name != "" {
		db = db.Where("name LIKE ?", "%"+name+"%")
	}
	if author != "" {
		db = db.Where("author LIKE ?", "%"+author+"%")
	}
	if category_id > 0 {
		db = db.Where("category_id = ?", category_id)
	}

	if available {
		db = db.Where("available > ?", 0)
	}

	err := db.Order("id desc").Find(&books).Error
	return books, err
}

func GetBook(id uint64) (*Book, error) {
	book := &Book{}

	err := database.DB.Model(Book{}).Where("id = ?", id).First(&book).Error

	return book, err
}

func (book *Book) CreateBook() error {
	err := database.DB.Create(&book).Error
	return err
}

func (book *Book) Save() error {
	err := database.DB.Save(&book).Error
	return err
}
